//get请求方法
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:dio/dio.dart';
import 'package:flutterApp/api/HttpManager.dart';

import '../main.dart';

get(url, {Map params,String loadingMessage="请求中"}) async {
  var extra = {"loadingMessage": loadingMessage};
  Options requestOptions = new Options(extra: extra);
  Response response;
  try {
    response = await HttpManager()
        .http
        .get(url, queryParameters: params, options: requestOptions);
    print('getHttp response: $response');
  } on DioError catch (e) {
    print('getHttp exception: $e');
    formatError(e);
  }
  return response;
}

//post请求
post(url, {Map params,String loadingMessage="请求中"}) async {
  var extra = {"loadingMessage": loadingMessage};
  Options requestOptions = new Options(extra: extra);
  Response response;
  try {
    response = await HttpManager()
        .http
        .post(url, queryParameters: params, options: requestOptions);
    print('postHttp response: $response');
  } on DioError catch (e) {
    print('postHttp exception: $e');
    formatError(e);
  }
  return response;
}

//post Form请求
postForm(url, {data, options}) async {
  Response response;
  try {
    response = await HttpManager().http.post(url, options: options, data: data);
    print('postHttp response: $response');
  } on DioError catch (e) {
    print('postHttp exception: $e');
    formatError(e);
  }
  return response;
}

//下载文件
downLoadFile(urlPath, savePath) async {
  Response response;
  try {
    response = await HttpManager().http.download(urlPath, savePath,
        onReceiveProgress: (int count, int total) {
      print('$count $total');
    });
    print('downLoadFile response: $response');
  } on DioError catch (e) {
    print('downLoadFile exception: $e');
    formatError(e);
  }
  return response;
}

//取消请求
cancleRequests(CancelToken token) {
  token.cancel("cancelled");
}

void formatError(DioError e) {
  if (e.type == DioErrorType.CONNECT_TIMEOUT) {
    showOkAlertDialog(
        context: navigatorKey.currentState.overlay.context, title: "连接超时");
    print("连接超时");
  } else if (e.type == DioErrorType.SEND_TIMEOUT) {
    showOkAlertDialog(
        context: navigatorKey.currentState.overlay.context, title: "请求超时");
    print("请求超时");
  } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
    showOkAlertDialog(
        context: navigatorKey.currentState.overlay.context, title: "响应超时");
    print("响应超时");
  } else if (e.type == DioErrorType.RESPONSE) {
    showOkAlertDialog(
        context: navigatorKey.currentState.overlay.context, title: "出现异常");
    print("出现异常");
  } else if (e.type == DioErrorType.CANCEL) {
    showOkAlertDialog(
        context: navigatorKey.currentState.overlay.context, title: "请求取消");
    print("请求取消");
  } else {
    showOkAlertDialog(
        context: navigatorKey.currentState.overlay.context, title: "未知错误");
    print("未知错误");
  }
}
